package com.example.app2;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.app2.pojo.CartInfo;
import com.example.app2.pojo.GoodsInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShoppingCartActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout goodsList;
    private ShoppingDBHelper mDBHelper;
    private Map<Integer, GoodsInfo> mGoodsMap=new HashMap<>();
    private TextView tv_total_price;
    private List<CartInfo> cartInfos;
    private TextView tv_count;
    private LinearLayout ll_empty;
    private View ll_content;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);
        TextView tv_title = findViewById(R.id.tv_title);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.btn_shopping_channel).setOnClickListener(this);
        findViewById(R.id.btn_clear).setOnClickListener(this);
        findViewById(R.id.btn_settle).setOnClickListener(this);
        goodsList = findViewById(R.id.ll_cart);
        ll_empty = findViewById(R.id.ll_empty);
        ll_content = findViewById(R.id.ll_content);
        mDBHelper = ShoppingDBHelper.getInstance(this);
        tv_total_price = findViewById(R.id.tv_total_price);
        tv_title.setText("购物车");
        tv_count = findViewById(R.id.tv_count);
        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));


    }

    @Override
    protected void onResume() {
        super.onResume();
        showCart();
    }

    private void showCart() {
        //移除下面所有子视图
        goodsList.removeAllViews();
        //查询所有购物车中的商品
        cartInfos = mDBHelper.queryAllCartInfo();

        for (CartInfo info : cartInfos) {
            GoodsInfo goodsInfo = mDBHelper.queryGoodsInfoById(info.goodsId);
            if(goodsInfo==null)
            {
                Log.d("tang", "showCart: 查询商品信息失败");
                return;
            }
            mGoodsMap.put(info.goodsId,goodsInfo);
            //获取item_cart.xml的根视图
            View view = LayoutInflater.from(this).inflate(R.layout.item_cart, null);
            ImageView iv_thumb = view.findViewById(R.id.iv_thumb);
            TextView tv_name = view.findViewById(R.id.tv_name);
            TextView tv_description = view.findViewById(R.id.tv_desc);
            TextView tv_count = view.findViewById(R.id.tv_count);
            TextView tv_price = view.findViewById(R.id.tv_price);
            TextView tv_sum = view.findViewById(R.id.tv_sum);
            iv_thumb.setImageURI(Uri.parse(goodsInfo.picPath));
            tv_name.setText(goodsInfo.name);
            tv_description.setText(goodsInfo.description);
            tv_count.setText(String.valueOf(info.count));
            tv_price.setText(String.valueOf(goodsInfo.price));
            //添加该商品的总价值
            tv_sum.setText(String.valueOf(goodsInfo.price*info.count));
            //添加到列表视图中
            goodsList.addView(view);
            //给商品添加长按事件，长按就删除
            view.setOnLongClickListener(v->{
                AlertDialog.Builder builder=new AlertDialog.Builder(this);
                builder.setMessage("是否从购物车中删除");
                builder.setPositiveButton("是",((dialog, which) -> {
                    //移除当前视图
                    goodsList.removeView(v);
                    deleteGoodsInfo(info);
                }));
                builder.setNegativeButton("否",null);
                builder.create().show();
                return true;
            });
            view.setOnClickListener(v->{
                Intent intent=new Intent(ShoppingCartActivity.this,ShoppingDetailActivity.class);
                intent.putExtra("goodsId",goodsInfo.id);
                startActivity(intent);
            });
        }
        showCount();
        reflashTotalPrice();

    }

    private void reflashTotalPrice() {
        int total_sum=0;
        for (CartInfo info : cartInfos) {
            total_sum+=mGoodsMap.get(info.goodsId).price * info.count;
        }
        tv_total_price.setText(String.valueOf(total_sum));
    }

    private void deleteGoodsInfo(CartInfo info) {
        //全局中的购物车数量减少
        MyApplication.getInstance().goodsCount-=info.count;
        //数据库中也要删除
        mDBHelper.deleteCartInfoById(info.goodsId);
        //类中关于删除购物车的信息也要删除
        cartInfos.remove(info);//?????????????????????
        mGoodsMap.remove(info.goodsId);
        showCount();
        Toast.makeText(this, "已从购物车中删除", Toast.LENGTH_SHORT).show();
        reflashTotalPrice();
    }

    private void showCount() {
        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));
        //购物车中没有商品，显示空空如也
        if(MyApplication.getInstance().goodsCount==0)
        {
            ll_empty.setVisibility(View.VISIBLE);
            ll_content.setVisibility(View.GONE);
            goodsList.removeAllViews();
        }
        else {
            ll_empty.setVisibility(View.GONE);
            ll_content.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_shopping_channel:
                finish();
                break;
            case R.id.btn_clear:
                MyApplication.getInstance().goodsCount=0;
                goodsList.removeAllViews();
                showCount();
                mDBHelper.deleteAllCartInfo();
                mGoodsMap.clear();
                cartInfos.clear();
                break;
            case R.id.btn_settle:
                AlertDialog.Builder builder=new AlertDialog.Builder(this);
                builder.setTitle("抱歉");
                builder.setMessage("暂时还没有开通结算业务，请下次再来");
                builder.setPositiveButton("确定", null);
                builder.create().show();
                break;
        }
    }
}
